<?php

use OSS\OssClient;

function showMsg($message = '', $status = 200, $data = array())
{
    $result = array(
        'code' => $status,
        'msg' => $message,
        'data' => $data
    );
    return response()->json($result);
}

function getDtime($time)
{
    $d2 = ceil(($time - time()) / 60 / 60 / 24);
    if ($d2 <= 0) {
        $chars[0] = "0";
        $chars[1] = "0";
    } else {
        $chars = preg_split('//', $d2, -1, PREG_SPLIT_NO_EMPTY);
    }
    return $chars;
}

function getAliOssImage($object)
{
    $accessKeyId = 'LTAI5tBdVwQoK1gnHH4WpA62';
    $accessKeySecret = 'SNoFsEcruIhy39XmejCnDNQY43B48L';
    $endpoint = 'https://oss-cn-beijing.aliyuncs.com'; // 例如：oss-cn-beijing.aliyuncs.com
    $customDomain = 'https://imgs.hnrcicchengfa.cn';
    $bucket = 'hnrcicchengfa';
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
    // 设置URL有效期（单位：秒），例如3600秒=1小时
    $timeout = 3600;
    // 生成带签名的临时访问URL
    $signedUrl = $ossClient->signUrl($bucket, $object, $timeout, OssClient::OSS_HTTP_GET, [], $customDomain);
    return $signedUrl;
}


function replaceImgSrc($html, $prefix = '')
{
    if (empty($html)) return $html;
    return preg_replace_callback('/<img[^>]+src=[\'"]([^\'"]+)[\'"]/i', function ($matches) use ($prefix) {
        $src = $matches[1];
        //dd($matches);
        $urls = delAliOssImage($src);
        return str_replace($src, $urls, $matches[0]);
    }, $html);
}

function replaceOssImgSrc($html, $prefix = '')
{
    if (empty($html)) return $html;
    return preg_replace_callback('/<img[^>]+src=[\'"]([^\'"]+)[\'"]/i', function ($matches) use ($prefix) {
        $src = $matches[1];
        //dd($matches);
        $urls = getAliOssImage(ltrim($src, '/'));
        return str_replace($src, $urls, $matches[0]);
    }, $html);
}


function delAliOssImage($object)
{
    $object = str_replace('https://hnrcicchengfa.oss-cn-beijing.aliyuncs.com/', '', $object);
    $json = explode('?', $object);
    if (count($json) > 0) {
        return $json[0];
    } else {
        return $object;
    }
}

function delJsonAliOssImage($object)
{
    $arys = [];
    foreach ($object as $value) {
        $array = str_replace('https://hnrcicchengfa.oss-cn-beijing.aliyuncs.com/', '', $value);
        $ary = explode('?', $array);
        if (count($ary) > 0) {
            array_push($arys, $ary[0]);
        }
    }
    return implode(',', $arys);
}


//获取周几
function getWeek($time = 0)
{
    if (empty($time)) {
        $time = time();
    }
    $weekarray = array("日", "一", "二", "三", "四", "五", "六");
    return "周" . $weekarray[date("w", $time)];
}

/**
 * 格式化数字
 */
function float_number($number)
{
    $length = strlen($number);  //数字长度
    if ($length > 8) { //亿单位
        $str = substr_replace(strstr($number, substr($number, -7), ' '), '.', -1, 0) . '亿';
    } elseif ($length > 4) { //万单位
        //截取前俩为
        $str = substr_replace(strstr($number, substr($number, -3), ' '), '.', -1, 0) . '万';
    } else {
        return $number;
    }
    return $str;
}

function addDomainToImages($html, $domain)
{
    // 确保域名末尾没有斜杠
    $domain = rtrim($domain, '/');
    // 正则表达式匹配img标签的src属性
    // 考虑各种可能的src写法：单引号、双引号、无引号
    $pattern = '/<img\s+[^>]*src=[\'"]([^\'"]+)[\'"]/i';
    // 替换回调函数
    $replaced = preg_replace_callback($pattern, function ($matches) use ($domain) {
        $src = $matches[1];
        // 已经是完整URL的不处理
        if (preg_match('/^https?:\/\//i', $src)) {
            return $matches[0];
        }
        // 处理相对路径
        $newSrc = $src;
        if (strpos($src, '/') !== 0) {
            $newSrc = '/' . $newSrc;
        }
        // 拼接域名和路径
        $newSrc = $domain . $newSrc;
        // 返回替换后的img标签部分
        return str_replace($matches[1], $newSrc, $matches[0]);
    }, $html);
    return $replaced;
}

//生成订单号
if (!function_exists('createGuid')) {
    function createGuid()
    {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);
        $uuid = substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);
        return $uuid;
    }
}

/*
 * 修改env配置文件
 * 2016-6-2 01:35:12
 */
function modifyEnv(array $data)
{
    $envPath = base_path() . DIRECTORY_SEPARATOR . '.env';
    $contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));
    $contentArray->transform(function ($item) use ($data) {
        foreach ($data as $key => $value) {
            if (str_contains($item, $key)) {
                if (strpos($key, 'BASE64') !== false) {
                    return $key . '=' . base64_encode($value);
                }
                return $key . '=' . $value;
            }
        }
        return $item;
    });
    $content = implode($contentArray->toArray(), "\n");
    \File::put($envPath, $content);
}

/**
 * 检测是否是手机号码
 * @param $mobile
 * @return bool
 */
function is_mobile($mobile)
{
    $preg = "/^1[3456789][0-9]{9}$/";
    if (preg_match($preg, $mobile)) {
        //验证通过
        return true;
    } else {
        //手机号码格式不对
        return false;
    }
}

//创建订单号
function create_trade_id()
{
    return date('ymd') . substr(time(), -3) . substr(microtime(), 2, 4) . str_pad(mt_rand(1, 99), 2, '0', STR_PAD_LEFT);
}

//创建激活码（16位）
function create_cards_code()
{
    // 取字符集数组
    $upperLetter = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    shuffle($upperLetter);
    $upperLetter = array_splice($upperLetter, 0, 32);
    shuffle($upperLetter);
    $str = implode('', $upperLetter);
    return $str;
}


/*
时分秒转秒
 *  */
function HisToS($his)
{
    $str = explode(':', $his);
    $len = count($str);
    if ($len == 3) {
        $time = $str[0] * 3600 + $str[1] * 60 + $str[2];
    } elseif ($len == 2) {
        $time = $str[0] * 60 + $str[1];
    } elseif ($len == 1) {
        $time = $str[0];
    } else {
        $time = 0;
    }
    return $time;
}


/**
 *      把秒数转换为时分秒的格式
 * @param Int $times 时间，单位 秒
 * @return String
 */
function secToTime($times)
{
    $result = '00:00:00';
    if ($times > 0) {
        $hour = floor($times / 3600);
        $minute = floor(($times - 3600 * $hour) / 60);
        $second = floor((($times - 3600 * $hour) - 60 * $minute) % 60);
        $result = $hour . ':' . $minute . ':' . $second;
    }
    return $result;
}

/*
字节转单位
 *  */
function calc($size, $digits = 2)
{
    $unit = array('', 'K', 'M', 'G', 'T', 'P');
    $base = 1024;
    $i = floor(log($size, $base));
    $n = count($unit);
    if ($i >= $n) {
        $i = $n - 1;
    }
    return round($size / pow($base, $i), $digits) . ' ' . $unit[$i] . 'B';
}

//计算两个时间戳直接相差的天数
function getTimeDays($etime)
{
    if ($etime) {
        $date = floor(($etime - time()) / 86400);
        if ($date <= 0) {
            $date = 0;
        }
    } else {
        $date = 0;
    }
    return $date;
}


// 显示前后文字，中间用*号替换
function hide_string($str)
{
    $covered = '';
    $str_length = strlen($str);
    $covered = substr($str, 0, $str_length / 3) . '****' . substr($str, strlen($str) - $str_length / 3);
    return $covered;
}

/**
 * 只保留字符串首尾字符，隐藏中间用*代替（两个字符时只显示第一个）
 * @param string $user_name 姓名
 * @return string 格式化后的姓名
 */
function substr_cut($user_name)
{
    $strlen = mb_strlen($user_name, 'utf-8');
    $firstStr = ucfirst(strtolower(mb_substr($user_name, 0, 1, 'utf-8')));
    $lastStr = strtolower(substr($user_name, -3));
    $result = "";
    if ($strlen == 2) {
        $hideStr = str_repeat('*', mb_strlen($user_name, 'utf-8') - 1);
        $result = $firstStr . $hideStr;
    } else if ($strlen == 1) {
        $result = $firstStr . '**';
    } else {
        $hideStr = str_repeat("*", $strlen - 2);
        $result = $firstStr . $hideStr . $lastStr;
    }
    return $result;
}

/**
 * 功能：字符串截取，支持中文截取
 * @str 文本字符
 * @start 开始截取的位置
 * @length 截取字符的长度
 * @return 返回截取后的字符
 */
function sub_string($str, $start, $length, $charset = 'utf-8', $suffix = true)
{
    $str = trim($str);
    $length = $length * 2;
    if ($length) {
        //截断字符
        $wordscut = '';
        if (strtolower($charset) == 'utf-8') {
            //utf8编码
            $n = 0;
            $tn = 0;
            $noc = 0;
            while ($n < strlen($str)) {
                $t = ord($str[$n]);
                if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1;
                    $n++;
                    $noc++;
                } elseif (194 <= $t && $t <= 223) {
                    $tn = 2;
                    $n += 2;
                    $noc += 2;
                } elseif (224 <= $t && $t < 239) {
                    $tn = 3;
                    $n += 3;
                    $noc += 2;
                } elseif (240 <= $t && $t <= 247) {
                    $tn = 4;
                    $n += 4;
                    $noc += 2;
                } elseif (248 <= $t && $t <= 251) {
                    $tn = 5;
                    $n += 5;
                    $noc += 2;
                } elseif ($t == 252 || $t == 253) {
                    $tn = 6;
                    $n += 6;
                    $noc += 2;
                } else {
                    $n++;
                }
                if ($noc >= $length) {
                    break;
                }
            }
            if ($noc > $length) {
                $n -= $tn;
            }
            $wordscut = substr($str, $start, $n);
        } else {
            for ($i = 0; $i < $length - 1; $i++) {
                if (ord($str[$i]) > 127) {
                    $wordscut .= $str[$i] . $str[$i + 1];
                    $i++;
                } else {
                    $wordscut .= $str[$i];
                }
            }
        }
        if ($wordscut == $str) {
            return $str;
        }
        return $suffix ? trim($wordscut) : trim($wordscut);
    } else {
        return $str;
    }
    $code = $code ?: I('vcode');
    if (empty($code)) {
        return 0;
    }
    return $code == $vcode['code'];
}

/**
 * 过滤标签，输出纯文本
 * @param string $str 文本内容
 * @return string 处理后内容
 * @author ubten <462193409@qq.com>
 */
function html2text($str)
{
    $alltext = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU", "", $str);
    $alltext = str_replace("　", " ", $alltext);
    $alltext = preg_replace("/&([^;&]*)(;|&)/", "", $alltext);
    $alltext = preg_replace("/style=.+?['|\"]/i", '', $alltext);
    $alltext = preg_replace("/class=.+?['|\"]/i", '', $alltext);
    $alltext = preg_replace("/<span[^>]*>/i", "", $alltext);
    $alltext = preg_replace("/<\/span>/i", "", $alltext);
    $alltext = preg_replace("/<strong[^>]*>/i", "", $alltext);
    $alltext = preg_replace("/title=.+?['|\"]/i", "", $alltext);
    $alltext = preg_replace("/alt=.+?['|\"]/i", "", $alltext);
    $alltext = preg_replace("/<img[^>]*>/i", "", $alltext);
    $alltext = preg_replace("/<\/strong>/i", "", $alltext);
    $alltext = preg_replace("/<p[^>]*>/i", "", $alltext);
    $alltext = preg_replace("/<\/p>/i", "", $alltext);
    $alltext = preg_replace("/<section[^>]*>/i", "", $alltext);
    $alltext = preg_replace("/<\/section>/i", "", $alltext);
    $alltext = preg_replace("/[ ]+/s", " ", $alltext);
    $alltext = preg_replace("/<br[^>]*>/i", "", $alltext); //过滤br标签
    $alltext = preg_replace("/<br>/i", "", $alltext); //过滤br标签
    return $alltext;
}

function get_img_thumb_url($content = "", $suffix = "/statics/images/product_2.jpg")
{
    $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
    //$content = preg_replace($pregRule, '<img src="${1}" style="max-width:100%">', $content);
    $content = preg_replace($pregRule, '<img src="${1}" style="max-width:100%;" >', $content);
    return $content;
}

function htmlTotext($str)
{
    $alltext = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU", "", $str);
    $alltext = str_replace("　", " ", $alltext);
    $alltext = preg_replace("/&([^;&]*)(;|&)/", "", $alltext);
    $alltext = preg_replace("/style=.+?['|\"]/i", '', $alltext);
    $alltext = preg_replace("/class=.+?['|\"]/i", '', $alltext);
    $alltext = preg_replace("/<span[^>]*>/i", "", $alltext);
    $alltext = preg_replace("/<\/span>/i", "", $alltext);
    $alltext = preg_replace("/<strong[^>]*>/i", "", $alltext);
//    $alltext = preg_replace("/<img[^>]*>/i", "", $alltext);
    $alltext = preg_replace("/<\/strong>/i", "", $alltext);
    $alltext = preg_replace("/<p[^>]*>/i", "", $alltext);
    $alltext = preg_replace("/<\/p>/i", "", $alltext);
    $alltext = preg_replace("/[ ]+/s", " ", $alltext);
//    $alltext = preg_replace("/<br[^>]*>/i", "", $alltext);
    return $alltext;
}

function htmlClearText($str)
{
    $alltext = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU", "", $str);
    $alltext = str_replace("　", " ", $alltext);
    $alltext = preg_replace("/&([^;&]*)(;|&)/", "", $alltext);
    $alltext = preg_replace("/style=.+?['|\"]/i", '', $alltext);
    $alltext = preg_replace("/class=.+?['|\"]/i", '', $alltext);
    $alltext = preg_replace("/<span[^>]*>/i", "", $alltext);
    $alltext = preg_replace("/<\/span>/i", "", $alltext);
    $alltext = preg_replace("/<strong[^>]*>/i", "", $alltext);
//    $alltext = preg_replace("/<img[^>]*>/i", "", $alltext);
    $alltext = preg_replace("/<\/strong>/i", "", $alltext);
//    $alltext = preg_replace("/<p[^>]*>/i", "", $alltext);
//    $alltext = preg_replace("/<\/p>/i", "", $alltext);
    $alltext = preg_replace("/[ ]+/s", " ", $alltext);
//    $alltext = preg_replace("/<br[^>]*>/i", "", $alltext);
    return $alltext;
}

//清除行高
function clear_lineHeight($content)
{
    $config = array('line-height', 'margin-right', 'margin-top', 'margin-left', 'margin-bottom', 'letter-spacing', 'text-indent', 'text-autospace', 'text-justify');
    foreach ($config as $v) {
        $content = preg_replace('/' . $v . '\s*=\s*\d+\s*/i', '', $content);
        $content = preg_replace('/' . $v . '\s*=\s*.+?["\']/i', '', $content);
        $content = preg_replace('/' . $v . '\s*:\s*\d+\s*%\s*;?/i', '', $content);
        $content = preg_replace('/' . $v . '\s*:\s*\d+\s*px\s*;?/i', '', $content);
        $content = preg_replace('/' . $v . '\s*:\s*\d;/i', '', $content);
        $content = preg_replace('/' . $v . '\s*:\w*-\w*;/i', '', $content);
    }
    $content = preg_replace('/style=""/i', '', $content);
    $content = preg_replace('/background: rgb(255, 255, 255);/i', '', $content);
    $content = preg_replace('/<p style=";"><span >&nbsp;<\/span><\/p>/i', '<br />', $content);
    $content = preg_replace('/<p style=";text-align:justify;"><span >&nbsp;<\/span><\/p>/i', '<br />', $content);
    $content = preg_replace('/<p style=";">&nbsp;<\/p>/i', '<br />', $content);
    $content = preg_replace('/<p ><span >&nbsp;<\/span><\/p>/i', '<br />', $content);
    return $content;
}

/**
 * 抽奖计算
 * @param $proArr 奖项列表
 */
function get_lucky_prize($proArr)
{
    $result = '';
    //概率数组的总概率精度
    $proSum = array_sum($proArr);
    //概率数组循环
    foreach ($proArr as $key => $proCur) {
        $randNum = mt_rand(1, $proSum);
        if ($randNum <= $proCur) {
            $result = $key;
            break;
        } else {
            $proSum -= $proCur;
        }
    }
    unset ($proArr);
    return $result;
}


function get_week_date($time = 0)
{
    if (!$time) {
        $time = time();
    }
    $week = date('w', $time);
    $weekname = array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
    return $weekname[$week];
}

/**
 * 获取一周日期
 * @param $time 时间戳
 * @param $format 转换格式
 */
function get_week_arr($day = 20, $time = 0)
{
    if (!$time) {
        $time = time();
    }
    for ($i = 0; $i < $day; $i++) {
        $currDay = ($day - 1) - $i;
        $data[$i] = date('Y-m-d', strtotime("-{$currDay} days", $time));
    }
    return json_encode($data);
}

//非常给力的authcode加密函数,Discuz!经典代码(带详解)
//函数authcode($string, $operation, $key, $expiry)中的$string：字符串，明文或密文；$operation：DECODE表示解密，其它表示加密；$key：密匙；$expiry：密文有效期。
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
    // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
    $ckey_length = 4;

    // 密匙
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);

    // 密匙a会参与加解密
    $keya = md5(substr($key, 0, 16));
    // 密匙b会用来做数据完整性验证
    $keyb = md5(substr($key, 16, 16));
    // 密匙c用于变化生成的密文
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
    // 参与运算的密匙
    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);
    // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，
    //解密时会通过这个密匙验证数据完整性
    // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    // 产生密匙簿
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    // 核心加解密部分
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        // 从密匙簿得出密匙进行异或，再转成字符
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'DECODE') {
        // 验证数据有效性，请看未加密明文的格式
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
        // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
        return $keyc . str_replace('=', '', base64_encode($result));
    }
}


/**
 * 友好的时间显示
 * @param int $sTime 待显示的时间
 * @param string $type 类型. normal | mohu | full | ymd | other
 * @param string $alt 已失效
 * @return string
 * @author jry <598821125@qq.com>
 */
function friendly_date($sTime, $type = 'normal', $alt = 'false')
{
    if (!$sTime)
        return '';
    //sTime=源时间，cTime=当前时间，dTime=时间差
    $cTime = time();
    $dTime = $cTime - $sTime;
    $dDay = intval(date("z", $cTime)) - intval(date("z", $sTime));
    $dDay = intval($dTime / 3600 / 24);
    $dYear = intval(date("Y", $cTime)) - intval(date("Y", $sTime));
    //normal：n秒前，n分钟前，n小时前，日期
    if ($type == 'normal') {
        if ($dTime < 60) {
            if ($dTime < 10) {
                return '刚刚';
            } else {
                return intval(floor($dTime / 10) * 10) . "秒前";
            }
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
            //今天的数据.年份相同.日期相同.
        } elseif ($dYear == 0 && $dDay == 0) {
            //return intval($dTime/3600)."小时前";
            return '今天' . date('H:i', $sTime);
        } elseif ($dYear == 0) {
            return date("m月d日 H:i", $sTime);
        } else {
            return date("Y-m-d H:i", $sTime);
        }
    } elseif ($type == 'mohu') {
        if ($dTime < 60) {
            return $dTime . "秒前";
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
        } elseif ($dTime >= 3600 && $dDay == 0) {
            return intval($dTime / 3600) . "小时前";
        } elseif ($dDay > 0 && $dDay <= 7) {
            return intval($dDay) . "天前";
        } elseif ($dDay > 7 && $dDay <= 30) {
            return intval($dDay / 7) . '周前';
        } elseif ($dDay > 30) {
            return intval($dDay / 30) . '个月前';
        }
        //full: Y-m-d , H:i:s
    } elseif ($type == 'full') {
        return date("Y-m-d , H:i:s", $sTime);
    } elseif ($type == 'ymd') {
        return date("Y-m-d", $sTime);
    } else {
        if ($dTime < 60) {
            return $dTime . "秒前";
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
        } elseif ($dTime >= 3600 && $dDay == 0) {
            return intval($dTime / 3600) . "小时前";
        } elseif ($dYear == 0) {
            return date("Y-m-d H:i:s", $sTime);
        } else {
            return date("Y-m-d H:i:s", $sTime);
        }
    }
}

// 无限分类算法
function getListTree($list, $pk = 'id', $pid = 'par_id', $child = 'children', $root = 0)
{
    if (!is_array($list)) {
        return [];
    }
    //创建基于主键的数组引用
    $aRefer = [];
    $tree = [];
    foreach ($list as $k => $v) {
        $aRefer[$v[$pk]] = &$list[$k];  // 主键id 作为数组下标
    }

    foreach ($list as $k => $v) {

        //判断是否存在parent
        $parentId = $v[$pid];
        if ($root === $parentId) {      // 当父id = 0 则是最外层
            $tree[] = &$list[$k];
        } else {                        // 当父id ！= 0 就创建 孩子层
            if (isset($aRefer[$parentId])) {    // 当该数据 的父亲数据存在时

                $parent = &$aRefer[$parentId];
                $parent[$child][] = &$list[$k]; // 为该父亲创建一个孩子层数据，孩子层数据就是该数据本身
            }
        }
    }
    return $tree;
}

function addBaseUrlToMedia($html, $baseUrl)
{
    // 处理图片标签
    $html = preg_replace_callback('/<img[^>]+src="([^"]+)"/i', function ($matches) use ($baseUrl) {
        $src = $matches[1];
        // 如果 src 不是完整的 URL，则添加基础网址
        if (!preg_match('/^https?:\/\//', $src)) {
            $src = rtrim($baseUrl, '/') . '/' . ltrim($src, '/');
        }
        return str_replace($matches[1], $src, $matches[0]);
    }, $html);

    // 处理视频标签
    $html = preg_replace_callback('/<video(?:\s+[^>]*?)?src="([^"]+)"/i', function ($matches) use ($baseUrl) {
        $src = $matches[1];
        // 如果 src 不是完整的 URL，则添加基础网址
        if (!preg_match('/^https?:\/\//', $src)) {
            $src = rtrim($baseUrl, '/') . '/' . ltrim($src, '/');
        }
        return str_replace($matches[1], $src, $matches[0]);
    }, $html);

    return $html;
}

